﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ShoppingList
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }

            List<ListBox> listboxes = new List<ListBox>()
            {
                this.FindName("FirstListBox") as ListBox,
                this.FindName("SecondListBox") as ListBox
            };
            listboxes.ForEach(lb =>
            {
                if (lb != null) lb.UpdateLayout();
            });
        }

        private void SwitchItem_Click(object sender, RoutedEventArgs e)
        {
            var item = (sender as Button).DataContext as ItemViewModel;
            if (item != null)
            {
                App.ViewModel.CurrentList.TransferItem(item);
                Microsoft.Devices.VibrateController.Default.Start(new TimeSpan(0, 0, 0, 0, 20));
            }
        }

        /// <summary>
        /// Gets or sets the edit button.
        /// </summary>
        /// <value>The edit button.</value>
        public ApplicationBarIconButton EditButton
        {
            get
            {
                if (ApplicationBar.Buttons.Count >= 2)
                    return ApplicationBar.Buttons[1] as ApplicationBarIconButton;
                else return null;
            }
        }

        /// <summary>
        /// Gets or sets the edit button.
        /// </summary>
        /// <value>The edit button.</value>
        public ApplicationBarIconButton DeleteButton
        {
            get
            {
                if (ApplicationBar.Buttons.Count >= 3)
                    return ApplicationBar.Buttons[2] as ApplicationBarIconButton;
                else return null;
            }
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
        }

        private void listItemSelected(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                App.ViewModel.CurrentList.CurrentItem = e.AddedItems[0] as ItemViewModel;

                SetButtonsState();
            }
            else if (e.RemovedItems.Count > 0)
            {
                App.ViewModel.CurrentList.CurrentItem = null;
                SetButtonsState();
            }
            Microsoft.Devices.VibrateController.Default.Start(new TimeSpan(0, 0, 0, 0, 2));
        }

        private void SetButtonsState()
        {
            EditButton.IsEnabled = App.ViewModel.CurrentList.CurrentItem != null;
            DeleteButton.IsEnabled = App.ViewModel.CurrentList.CurrentItem != null;
        }

        private void ApplicationBarAddItemButton_Click(object sender, EventArgs e)
        {
            App.ViewModel.CurrentList.CurrentItem = null;
            FirstListBox.SelectedItem = null;
            SecondListBox.SelectedItem = null;

            List<ListBox> listboxes = new List<ListBox>()
            {
                this.FindName("FirstListBox") as ListBox,
                this.FindName("SecondListBox") as ListBox
            };
            listboxes.ForEach(lb =>
            {
                if (lb != null) lb.SelectedItem = null;
            });

            NavigationService.Navigate(new Uri("/EditItemPage.xaml", UriKind.Relative));
        }

        private void ApplicationBarEditItemButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/EditItemPage.xaml", UriKind.Relative));
        }

        private void ApplicationBarDeleteButton_Click(object sender, EventArgs e)
        {
            bool deleted =
                App.ViewModel.CurrentList.ItemsInCart.Remove(App.ViewModel.CurrentList.CurrentItem) ||
                App.ViewModel.CurrentList.ItemsOnList.Remove(App.ViewModel.CurrentList.CurrentItem);
            App.ViewModel.CurrentList.OnPropertyChanged("CartSum");
            App.ViewModel.CurrentList.OnPropertyChanged("ListSum");
        }

        private void StackPanel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //(sender as StackPanel).Children[1].Visibility = System.Windows.Visibility.Visible;
            //((sender as StackPanel).Children[0] as TextBlock).Style = App.Current.RootVisual.
            //((sender as StackPanel).Children[0] as TextBlock).TextDecorations = TextDecorations.Underline;
        }

        private void ListBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //(sender as ListBox).SelectedItem = null;
        }

        private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.RemovedItems.Count > 0
                && (e.RemovedItems[0] as PivotItem) != null
                && ((e.RemovedItems[0] as PivotItem).Content as ListBox) != null)
            {
                ((e.RemovedItems[0] as PivotItem).Content as ListBox).SelectedItem = null;
            }
            //var items = new List<ItemViewModel>() {
            //(FirstListBox.SelectedItem as ItemViewModel),
            //(SecondListBox.SelectedItem as ItemViewModel)
            //};
            //items.ForEach(i => { if (i != null)i.NotifyPropertyChanged("Selected"); });
            var listbox = (((e.AddedItems[0] as PivotItem).Content as Grid).Children.First(c => c.GetType() == typeof(ListBox)) as ListBox);
            if (listbox != null)
            {
                if (listbox.Items.Contains(App.ViewModel.CurrentList.CurrentItem))
                {
                    listbox.SelectedItem = App.ViewModel.CurrentList.CurrentItem;
                }
                else
                {
                    var item = (listbox.SelectedItem as ItemViewModel);
                    if (item != null)
                    {
                        App.ViewModel.CurrentList.CurrentItem = item;
                    }
                }
            }

            //FirstListBox.SelectedIndex = -1;
            //SecondListBox.SelectedIndex = -1;
            //App.ViewModel.CurrentList.CurrentItem = null;
            //SetButtonsState();
        }

        private void ApplicationBarListsIconButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Lists.xaml", UriKind.Relative));
        }

        private void ApplicationBarMenuItemHelp_Click(object sender, EventArgs e)
        {
            MessageBox.Show(ShoppingList.Resources.MainPage_Help, ShoppingList.Resources.Help, MessageBoxButton.OK);
        }

        private void btn_sendviaemail_Click(object sender, EventArgs e)
        {
            ListViewModel.MailContent content = ListViewModel.MailContent.All;
            if (itemspivot.SelectedItem == onlist)
            {
                content = ListViewModel.MailContent.List;
            }
            else if (itemspivot.SelectedItem == incart)
            {
                content = ListViewModel.MailContent.Cart;
            }
            App.ViewModel.CurrentList.SendViaEmail(null, content);
        }

        private void btn_sortitemsbyname_Click(object sender, EventArgs e)
        {
            SortItemsOnSelectedPage(ItemViewModel.NameComparison);

            //if (itemspivot.SelectedItem == onlist)
            //{
            //    itemstosort = App.ViewModel.CurrentList.ItemsOnList.ToList();
            //    itemstosort.Sort(comparison);
            //    App.ViewModel.CurrentList.ItemsOnList = new System.Collections.ObjectModel.ObservableCollection<ItemViewModel>();
            //    itemstosort.ForEach(i => App.ViewModel.CurrentList.ItemsOnList.Add(i));
            //    App.ViewModel.CurrentList.OnPropertyChanged("ItemsOnList");
            //}
            //else if (itemspivot.SelectedItem == incart)
            //{
            //    itemstosort = App.ViewModel.CurrentList.ItemsInCart.ToList();
            //    itemstosort.Sort(comparison);
            //    App.ViewModel.CurrentList.ItemsInCart = new System.Collections.ObjectModel.ObservableCollection<ItemViewModel>();
            //    itemstosort.ForEach(i => App.ViewModel.CurrentList.ItemsInCart.Add(i));
            //    App.ViewModel.CurrentList.OnPropertyChanged("ItemsInCart");
            //}
        }

        private void btn_sortitemsbyprice_Click(object sender, EventArgs e)
        {
            SortItemsOnSelectedPage(ItemViewModel.PriceComparison);
        }

        private void btn_sortitemsbyunitprice_Click(object sender, EventArgs e)
        {
            SortItemsOnSelectedPage(ItemViewModel.UnitPriceComparison);
        }

        private void SortItemsOnSelectedPage(Comparison<ItemViewModel> comparison)
        {
            bool listcase = itemspivot.SelectedItem == onlist;
            App.ViewModel.CurrentList.CurrentItem = null;
            var items = listcase ? App.ViewModel.CurrentList.ItemsOnList.ToList() :
                App.ViewModel.CurrentList.ItemsInCart.ToList();
            items.Sort(comparison);
            if (listcase)
            {
                App.ViewModel.CurrentList.ItemsOnList = new System.Collections.ObjectModel.ObservableCollection<ItemViewModel>();
                items.ForEach(i => App.ViewModel.CurrentList.ItemsOnList.Add(i));
            }
            else
            {
                App.ViewModel.CurrentList.ItemsInCart = new System.Collections.ObjectModel.ObservableCollection<ItemViewModel>();
                items.ForEach(i => App.ViewModel.CurrentList.ItemsInCart.Add(i));
            }
            App.ViewModel.CurrentList.OnPropertyChanged(listcase ? "ItemsOnList" : "ItemsInCart");
        }
    }
}